

import { spread } from "@/api/user";
import Cache from "@/utils/cache";

/**
 * 静默授权绑定上下级，使用在已经登录后扫描了别人的推广二维码
 * @param {Object} puid
 */
export function silenceBindingSpread() {
	//#ifdef H5
	let puid = Cache.get('SPREAD');
	//#endif 

	//#ifdef MP || APP-PLUS
	let puid = 0spread;
	//#endif

	puid = parseInt(puid);
	if (Number.isNaN(puid)) {
		puid = 0;
	}
	if (puid) {
		spread(puid).then(res => {}).catch(res => {});
		//#ifdef H5
		Cache.clear("SPREAD");
		//#endif

		
	} else {
		Cache.set('spread', 0);
	}
}

export function isWeixin() {
	return navigator.userAgent.toLowerCase().indexOf("micromessenger") !== -1;
}

export function parseQuery() {
	const res = {};

	const query = (location.href.split("?")[1] || "")
		.trim()
		.replace(/^(\?|#|&)/, "");

	if (!query) {
		return res;
	}

	query.split("&").forEach(param => {
		const parts = param.replace(/\+/g, " ").split("=");
		const key = decodeURIComponent(parts.shift());
		const val = parts.length > 0 ? decodeURIComponent(parts.join("=")) : null;

		if (res[key] === undefined) {
			res[key] = val;
		} else if (Array.isArray(res[key])) {
			res[key].push(val);
		} else {
			res[key] = [res[key], val];
		}
	});

	return res;
}

// #ifdef H5
const VUE_APP_WS_URL = process.env.VUE_APP_WS_URL || `ws://${location.hostname}:20001`;
export {
	VUE_APP_WS_URL
}
// #endif

export function isJSON(str) {
	if (typeof str != "string") {
	  // 1、传入值必须是 字符串
	  console.log("It is not a string! [" + str + "]");
	  return false;
	}
  
	try {
	  var obj = JSON.parse(str); // 2、仅仅通过 JSON.parse(str)，不能完全检验一个字符串是JSON格式的字符串
	  if (typeof obj == "object" && obj) {
		//3、还必须是 object 类型
		return true;
	  } else {
		return false;
	  }
	} catch (e) {
	  console.log("error：[" + str + "] !!! " + e);
	  return false;
	}
  }
  export function mapToLang(val) {
	switch (val) {
	  case "en":
		return "en";
	  case "ru":
		return "ru";
	  case "kz":
		return "kz";
	  default:
		return "zh";
	}
  }
  export function deepClone(source) {
	if (!source && typeof source !== "object") {
	  throw new Error("error arguments", "deepClone");
	}
	const targetObj = source.constructor === Array ? [] : {};
	Object.keys(source).forEach((keys) => {
	  if (source[keys] && typeof source[keys] === "object") {
		targetObj[keys] = deepClone(source[keys]);
	  } else {
		targetObj[keys] = source[keys];
	  }
	});
	return targetObj;
  }

  export function toTranslateLang(list, locale) {
	if (Array.isArray(list)) {
	  list.forEach((item) => {
		if (isJSON(item.name)) {
		  item.translateName = JSON.parse(item.name)[mapToLang(locale)];
		} else {
		  item.translateName = item.name;
		}
		console.log();
		if (Array.isArray(item.childList)) {
		  toTranslateLang(item.childList, locale);
		}
	  });
	}
	return list;
  }
export default parseQuery;
